

class Ble{

  static server = undefined
  static init = false

  static initBle(callback){    
    if(!this.init){
      this.init = true
      this.enableBle(callback);
      wx.onBluetoothAdapterStateChange((result) => {
        if(result.available && this.server == undefined){
            this.createPeripheralServer()
        }
      })
    }
  }

  static createPeripheralServer(){
    wx.createBLEPeripheralServer({
      success: (result) => {
        this.server = result.server
      },
      fail: (res) => {
        console.log(" create ble central server failed "+JSON.stringify(res))
      },
      complete: (res) => {
        console.log(" create ble central server complete "+JSON.stringify(res))
      },
    })
  }

  static enableBle(callback){
    wx.openBluetoothAdapter({
      mode: 'peripheral',
      success: (res)=>{
        this.createPeripheralServer()
        if(callback!=undefined || callback!=null){
          callback.success(res)
        }
      },
      fail: (error)=>{
        console.log(" open peripheral bluetooth adapter failed "+JSON.stringify(error))
        callback.fail(error)
      },
      complete: (res)=>{
        console.log(" open peripheral bluetooth adapter complete "+JSON.stringify(res))
      }
    })

    wx.openBluetoothAdapter({
      mode: 'central',
      success: (res) => {
        console.log(" enable succeed peripheral "+JSON.stringify(res))
      },
      fail: (res) =>{
        console.log(" open central bluetooth adapter failed "+JSON.stringify(res))
        if(callback!=undefined || callback!=null){
          callback.fail(res)
        }
      },
      complete: (res)=>{
        console.log(" open central bluetooth adapter complete "+JSON.stringify(res))
      }
    })
    
  }



  static disable(){
    wx.closeBluetoothAdapter({
      success: (res) => {
        console.log(JSON.stringify(res));
      },
    })
   
  }

}
const _Ble = Ble;
export { _Ble as Ble };